package com.itheima.sh.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;
    @GetMapping("{id}")
    public Map queryById(@PathVariable("id") String id){
        //1.根据应用名称获取注册列表，注册列表中存储着的是主机地址和端口号，
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        //2.list第一个元素索引是0
        ServiceInstance serviceInstance = instances.get(0);
        //3.获取主机名，端口号。url
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
//        String uri = serviceInstance.getUri().toString();

        //String url = "http://localhost:8081/user/" + id;  拿到主机地址端口号url之后就可以不用硬编码了
        // 调用RestTemplate的getForObject方法，指定url地址和返回值类型
//        Map user = restTemplate.getForObject(uri+"/user/"+id, Map.class);

        String url="http://"+host+":"+port+"/user/"+id;
        Map user = restTemplate.getForObject(url, Map.class);
        System.out.println("user = " + user);
        return user;
    }
}
